Daisy-chained Assignments

Not all JavaScript programmers may be aware of the fact that it is possible to do "daisy-chained" assignment statements in JavaScript, such as the following...

myVariable1 = myVariable2 = myVariable3 = myVariable4 = 0;

This statement assigns all the variables with the value 0. As another example, the following statements...

myVariable1 = myOtherVariable1 * myOtherVariable2 - myOtherVariable3;
myVariable2 = myVariable1;

...could be reduced to...

myVariable1 = myVariable2 = myOtherVariable1 * myOtherVariable2 - myOtherVariable3;

Of course, beware of using this syntax with object constructors such as "new Array ()". For example, the statements...

myArray1 = new Array ();
myArray2 = new Array ();

...is NOT the same as...

myArray1 = myArray2 = new Array ();

In the first case, both myArray1 and myArray2 will reference distinct new Array objects, but in the second case, both variables will reference the same shared Array object - only one new Array object is created! This is because objects in JavaScript are assigned to variables by reference. So, if you have an array called myArray1, then the statement...

myArrayRef1 = myArray1;

...does NOT actually create a duplicate of the object myArray1 and place it in myArrayRef1, but actually just lets myArrayRef1 point to the same "stash" in memory as myArray1. If you use myArrayRef1 to update the array by adding elements, the changes will be seen when you refer to the array by myArray1 as well.

So, if your intention is to link two (or more) variables to the same object, then the condensed syntax is appropriate. For example,...

myArray1 = new Array ();
myArrayRef1 = myArray1;
myArrayRef2 = myArray1;

...is indeed the same as the statement...

myArrayRef1 = myArrayRef2 = myArray1 = new Array ();

Now, all the variables will reference the same array object, so...

alert (myArray1 [0]);

...and...

alert (myArrayRef1 [0]);

...will show the same value. Use this wisdom cautiously!